<?php

namespace Core;

/**
 * Description of Routers
 *
 * @author Admin
 */
class Routers
{
	private static $_instance;


	protected $_routers = array();
	
	/**
	 * Router configs
	 * @var string
	 */
	protected $_configs = array();
	
	protected $_defaultModule = 'general';
	protected $_defaultController = 'index';
	protected $_defaultAction = 'index';

	protected $_module = 'default';
	protected $_controller = 'index';
	protected $_action = 'index';
	
	protected $_lang = '';
	protected $_allowLangs = array();
	
	protected $_router = '';

	/**
	 * 
	 * @return \Core\Routers
	 */
	public static function getInstance()
	{
		if(!self::$_instance)
			self::$_instance = new self;
		
		return self::$_instance;
	}

	public function configs($configs = null)
	{
		if($configs)
			$this->_configs = $configs;
		
		return $this->_configs;
	}		

	public function process($routers)
	{
		$this->_routers = $routers;
		$this->_router = $this->_searchRouter($_SERVER['REQUEST_URI']);

		if(!$this->_router)
		{
			$this->_router = $this->_getRouteByRequest($_SERVER['REQUEST_URI']);
		}
	}
	
	protected function _searchRouter($request)
	{
		$requestParts = explode('/', trim($request, '/'));
		
		if($this->_configs['multilang'] && isset($requestParts[0]) && preg_match('/^[a-z]{2}$/i', $requestParts[0]))
		{
			if(isset($this->_allowLangs[$requestParts[0]]))
			{
				$_GET['lang'] = $this->_lang = $requestParts[0];
				$requestParts = array_slice($requestParts, 1);
			}
		}
		
		$aCounts = array();
		foreach($this->_routers as $routerName => $router)
		{
			if(!isset($router[0]))
				continue;
			
			$routerParts = explode('/', trim($router[0], '/'));

			if(!count($requestParts) && !count($routerParts) && isset($router[1]))
			{
				$this->_module		= !empty($router[1]['module'])		? $router[1]['module']		: $this->_defaultModule;
				$this->_controller	= !empty($router[1]['controller'])	? $router[1]['controller']	: $this->_defaultController;
				$this->_action		= !empty($router[1]['action'])		? $router[1]['action']		: $this->_defaultAction;
				
				return $routerName;
			}
			
			$countEq = 0;
			$countNeed = 0;
			foreach($routerParts as $key => $part)
			{
				$var = '';
				
				if($part[0] == ':')
				{
					$var = mb_substr($part, 1);
					
					if(!isset($requestParts[$key]) && isset($router[1][$var]))
					{
						$_GET[$var] = $router[1][$var];
						$countEq++;
					}
					elseif(isset($requestParts[$key]) && (!isset($router[2]) || !isset($router[2][$var])))
					{
						$_GET[$var] = $part;
					}
					elseif(isset($requestParts[$key]) && isset($router[2]) && isset($router[2][$var]) && mb_ereg_match('^'.$router[2][$var].'$', $requestParts[$key]))
					{
						$_GET[$var] = $requestParts[$key];
						$countEq++;
						$countNeed++;
					}
					else
					{
						$countNeed++;
						$countEq--;
					}
				}
				else if(isset($requestParts[$key]) && $requestParts[$key] == $part)
				{
					$countEq++;
					$countNeed++;
				}
				else
				{
					$countNeed++;
					$countEq--;
				}
			}
			
			if($countEq >= $countNeed)
			{
				$this->_module		= !empty($router[1]['module'])		? $router[1]['module']		: $this->_defaultModule;
				$this->_controller	= !empty($router[1]['controller'])	? $router[1]['controller']	: $this->_defaultController;
				$this->_action		= !empty($router[1]['action'])		? $router[1]['action']		: $this->_defaultAction;
				
				$aCounts[$countEq] = $routerName;
//				return $routerName;
			}
			
		}
		
		$router = '';
		$max = 0;
		foreach($aCounts as $c => $routerName)
		{
			if($c >= $max)
			{
				$max = $c;
				$router = $routerName;
			}
		}
		
		return $router;
	}
	
	protected function _getRouteByRequest($request)
	{
		$request = trim($request, '/');
		$requestParts = $request ? explode('/', $request) : array();
		
		$this->_module		= $this->_defaultModule;
		$this->_controller	= $this->_defaultController;
		$this->_action		= $this->_defaultAction;

		$index = 0;
		
		if(isset($requestParts[0]) && $this->_configs['multilang'] && preg_match('/^[a-z]{2}$/i', $requestParts[0]))
		{
			if(isset($this->_allowLangs[$requestParts[0]]))
			{
				$_GET['lang'] = $this->_lang = $requestParts[0];

				$requestParts = array_slice($requestParts, 1);
			}
		}

		if(count($requestParts) >= 3)
		{
			$this->_module		= $requestParts[0];
			$this->_controller	= $requestParts[1];
			$this->_action		= $requestParts[2];
			
			if(count($requestParts) > 3)
			{
				for($i = 3, $c = count($requestParts); $i < $c; $i+=2)
				{
					$_GET[$requestParts[$i]] = isset($requestParts[$i+1]) ? $requestParts[$i+1] : null;
				}
			}

			return true;
		}
		else if(count($requestParts) == 2)
		{
			$this->_controller	= $requestParts[0];
			$this->_action		= $requestParts[1];
			
			return true;
		}
		else if(count($requestParts) == 1)
		{
			$this->_action		= $requestParts[0];
			
			return true;
		}
		else if(count($requestParts) == 0)
		{
			return true;
		}
		
		return false;
	}
	
	public function setAllowLangs($langs)
	{
		$this->_allowLangs = $langs;
	}
	
	/**
	 * 
	 * @return string
	 */
	public function getModuleName()
	{
		return $this->_module;
	}
	
	/**
	 * 
	 * @return string
	 */
	public function getControllerName()
	{
		return $this->_controller;
	}
	
	/**
	 * 
	 * @return string
	 */
	public function getActionName()
	{
		return $this->_action;
	}
	
	/**
	 * 
	 * @return string
	 */
	public function getLang()
	{
		return $this->_lang;
	}

	public function getUrlByRoute($router, $params = array())
	{
		if(!isset($this->_routers[(string)$router]))
			return '';
		
		$router = $this->_routers[$router];
		
		$url = $router[0];
		
		if($this->_allowLangs)
			$url = \Core\Langs::getLang () .'/'. ltrim($url, '/');
		
		foreach($params as $key => $val)
		{
			$url = preg_replace('/:'.$key.'/', $val, $url);
		}

		if(isset($router[2]) && count($router[2]))
		{
			foreach($router[2] as $key => $val)
			{
				if(!isset($params[$key]))
				{
					if(isset($router[1][$key]))
						$url = preg_replace('/:'.$key.'/', $router[1][$key], $url);
					else
						$url = preg_replace('/:'.$key.'/', '', $url);
				}
				
				else 
					if(!preg_match('/^'. $val .'$/', $params[$key]))
						throw new \Core\Exception('is not match param: '. $key);
			}
		}
		
		$url = preg_replace('/(:[a-zA-Z0-9-_]+)+/', '', $url);
		$url = trim($url, '/');
		
		return '/'. $url .(strlen($url) > 0 ? '/' : '');
	}
	
}
